import { Component, OnInit } from '@angular/core'
import { Location } from '@angular/common'
import { Router } from '@angular/router'
import { CommonUtil } from 'src/app/common/utils/common.util'
import { CoolLocalStorage } from 'src/app/common/coolStorage/cool-local-storage'
import { Modal } from 'ng-zorro-antd-mobile'

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.scss'],
  providers: [Modal]
})
export class SearchComponent implements OnInit {
  // 关键词
  keyword = ''
  // 热搜
  hot = []
  // 搜索历史
  history = []

  constructor(
    private location: Location,
    private router: Router,
    private utils: CommonUtil,
    private localStorage: CoolLocalStorage,
    private modal: Modal
  ) {}

  // 初始化
  ngOnInit() {
    this.getHot()
    this.getHistory()
  }
  // 返回
  onClickLeft() {
    this.location.back()
  }
  // 回车搜索
  handleKeypress(e) {
    let value = e.target.value
    let history: any = this.localStorage.getObject('searchHistory')
    // 如果按的是回车
    if (e.keyCode === 13) {
      // 如果输入了搜素内容
      if (e.target.value.length > 0) {
        this.router.navigate(['/workspace/home/searchResult', { keyword: value }])
        // 如果本地已经有历史记录
        if (history && history.length > 0) {
          let index = history.indexOf(value)
          // 如果本次搜索的已存在，那么把这条记录放在最前面
          if (index > -1) {
            history.splice(index, 1)
          }
          history.unshift(value)
        } else {
          history = [value]
        }
        this.localStorage.setObject('searchHistory', history)
      } else {
        this.utils.info('请输入搜索内容')
      }
    }
  }
  // 获取热搜
  getHot() {
    let config: any = this.localStorage.getObject('config')
    if (config && config.Hot) {
      this.hot = config.Hot
    }
  }
  // 获取搜索历史
  getHistory() {
    let history: any = this.localStorage.getObject('searchHistory')
    if (history && history.length > 0) {
      this.history = history
    }
  }
  // 设置关键词
  setKeyword(item) {
    this.keyword = item
    this.router.navigate(['/workspace/home/searchResult', { keyword: item }])
  }
  // 清除搜索历史
  clearHistory() {
    Modal.alert('提示', '是否确定要清空搜索历史？', [
      {
        text: '取消',
        onPress: () => {}
      },
      {
        text: '确定',
        onPress: () =>
          new Promise(resolve => {
            this.history = []
            this.localStorage.removeItem('searchHistory')
            this.utils.success('搜索历史已清空')
            resolve()
          })
      }
    ])
  }
}
